import {
  Component,
  Input,
  TemplateRef,
  ChangeDetectionStrategy,
  ViewEncapsulation,
  ViewChild,
  ContentChild,
  SimpleChanges,
  OnChanges,
  OnDestroy,
} from '@angular/core';
import { Subject } from 'rxjs';
import { v4 as uuid } from 'uuid';
import { InputBoolean } from '../core/api';
import { TabLazyDirective } from './tab.lazy.directive';

@Component({
  selector: 'lv-tab, [lv-tab]',
  exportAs: 'lvTab',
  template: '<ng-template #tabBodyTemplate><ng-content></ng-content></ng-template>',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  host: {},
})
export class TabComponent implements OnChanges, OnDestroy {
  @Input() lvId: string | number;

  @Input() lvClosable: boolean = null;

  @Input() lvTitle: string | TemplateRef<any>;

  @Input() lvDropdownLabel: string | TemplateRef<any>;

  @Input() lvTabClass: string = null;

  @Input() @InputBoolean() lvDisabled: boolean = false;

  @ViewChild('tabBodyTemplate', { static: false }) content: TemplateRef<void>;

  @ContentChild(TabLazyDirective, { read: TemplateRef, static: false }) lazyContent: TemplateRef<void>;

  // index在tabs.component组件用到，在此处定义
  public index;

  public hidden = false;

  // 保证每个tab唯一性
  public tabId: string = uuid();

  public change$ = new Subject<void>();

  public destroy$ = new Subject<void>();

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.lvTitle || changes.lvDisabled) {
      this.change$.next();
    }
  }
}
